package com.github.ylt.protocol.http;

import com.github.ylt.protocol.request.Request;
import com.github.ylt.utils.ByteUtils;
import com.github.ylt.utils.RequestUtils;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

public class HttpServerRead {
    private final SocketChannel socketChannel;
    private final ByteBuffer read = ByteBuffer.allocate(1024);
    private final ByteBuffer buffer = ByteBuffer.allocate(10000);
    private final SelectionKey key;
    public HttpServerRead(SocketChannel socketChannel, SelectionKey key) {
        this.socketChannel = socketChannel;
        this.key = key;
    }

    public void read() {
        boolean subcontract = false;
        try {
            while (socketChannel.read(read) > 0) {
                if(!read.hasRemaining()){
                    System.out.println("数据被分包,继续读取剩余的数据");
                    subcontract = true;
                    read.flip();
                    buffer.put(read.array());
                    read.clear();
                    continue;
                }else{
                    System.out.println("subcontract:"+subcontract);
                    buffer.put(read.array());
                }
                String data = ByteUtils.getInstance().bytesToString(buffer.array());
                System.out.println(Arrays.toString(data.split("\r\n")));
                System.out.println("长度："+data.length());
               // 处理多余的数据
                if(data.indexOf("</s:Envelope>")!=-1){
                    data = data.substring(0,data.indexOf("</s:Envelope>")+"</s:Envelope>".length());
                }
                buffer.flip();
                Request headerFields = RequestUtils.getInstance().getHeaderFields(data);
                headerFields.setSocketChannel(socketChannel);
                new HttpServerWirter(headerFields).run();
                read.clear();
                buffer.clear();
                subcontract = false;

            }

        } catch (IOException e) {
            try {
                socketChannel.close();
                key.cancel();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}
